package com.lovepick.database;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.lovepick.bean.Friend;


public class FriendDbManager
{
	private static final String TAG = "FriendDbManager";
	private SQLiteDatabase mDatabase = null;
	private DatabaseHelper mDbHelper = null;
	
	public FriendDbManager()
	{
		mDbHelper = new DatabaseHelper();
	}
	
	public List<Friend> getFriends()
	{
		Log.i(TAG, "---getFriends---");
		List<Friend> friends = null;
		String sql = "SELECT * FROM " + FriendTable.TABLE_NAME;
		try
		{
			mDatabase = mDbHelper.getReadableDatabase();
			Cursor cursor = mDatabase.rawQuery(sql, null);
			friends = new ArrayList<Friend>();
			boolean none = true;
			while (cursor.moveToNext())
			{
				none = false;
				Friend friend = new Friend();
				friend.setId(cursor.getInt(cursor.getColumnIndex(FriendTable.USER_ID)));
				friend.setNickName(cursor.getString(cursor.getColumnIndex(FriendTable.NICKNAME)));
				friend.setAvatar(cursor.getInt(cursor.getColumnIndex(FriendTable.AVATAR)));
				friend.setStatus(cursor.getString(cursor.getColumnIndex(FriendTable.STATUS)));
				friends.add(friend);
			}
			if (none)
			{
				friends = null;
			}
			mDatabase.close();
			
		}
		catch (Exception e)
		{
			// TODO: handle exception
			friends = null;
		}
		return friends;
	}
	
	public void addFriends(List<Friend> friends)
	{
		Log.i(TAG, "---addFriends---");
		try
		{
			mDatabase = mDbHelper.getWritableDatabase();
			
			for (Friend friend : friends)
			{
				ContentValues values = new ContentValues();
				values.put(FriendTable.USER_ID, friend.getId());
				values.put(FriendTable.NICKNAME, friend.getNickName());
				values.put(FriendTable.AVATAR, friend.getAvatar());
				values.put(FriendTable.STATUS, friend.getStatus());
				mDatabase.insert(FriendTable.TABLE_NAME, null, values);
			}
			mDatabase.close();
		}
		catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public void updateFriend(Friend friend)
	{
		Log.i(TAG, "---updateFriend---");
		String whereClause = FriendTable.USER_ID + "=?";
		String[] whereArgs = new String[] {String.valueOf(friend.getId())};
		try
		{
			mDatabase = mDbHelper.getWritableDatabase();
			ContentValues values = new ContentValues();
			values.put(FriendTable.USER_ID, friend.getId());
			values.put(FriendTable.NICKNAME, friend.getNickName());
			values.put(FriendTable.AVATAR, friend.getAvatar());
			values.put(FriendTable.STATUS, friend.getStatus());
			mDatabase.update(FriendTable.TABLE_NAME, values, whereClause, whereArgs);
		}
		catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
}
